export function validateRequired(
  rule,
  value,
  callback,
  { label, trim } = { label: "", trim: false }
) {
  let val = String(value ?? "");
  if (trim) val = val.trim();

  if (val.length === 0) {
    callback(new Error(`请输入${label}`));
  } else {
    callback();
  }
}

export function validateAccount(rule, value, callback) {
  const val = String(value ?? "");
  if (!val) {
    callback(new Error("请输入用户名"));
  } else if (/[A-Za-z][A-Za-z0-9_]{5,29}/.test(val)) {
    callback();
  } else {
    callback(
      new Error(
        `用户名只能填写字母、数字、下划线，开头必须为字母，且长度在6~30位内！`
      )
    );
  }
}

export function validatePassword(rule, value, callback) {
  const val = String(value ?? "");
  if (!val) {
    callback(new Error("请输入密码"));
  } else if (
    /(?!^\d+$)(?!^[A-Za-z]+$)(?!^_+$)^\w{6,30}$/.test(String(value ?? ""))
  ) {
    callback();
  } else {
    callback(
      new Error(
        `密码格式错误，必须且只能包含字母、数字、下划线中的两种或两种以上`
      )
    );
  }
}

export function validatePasswordConfirm(rule, value, callback, password) {
  const val = String(value ?? "");
  if (!val) {
    callback(new Error("请再次输入密码"));
  } else if (val !== password) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
}
